import store from '@/store';
import { isXxtb } from '@/config/config';
import router from '@/router';
import http from './fetch';
import Vue from 'vue';
import { Base64 } from '@/utils/base64';

/**
 * base64图片转File对象
 * baseStr: 图片base64编码
 * filename: 转换后文件名，true:生成随机名字
 * */

function base2img(baseStr, filename = true) {
  let arr = baseStr.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  filename === true && (filename = `file_${(Math.random() * 9999) | 0}.${mime.split('/')[1]}`);
  return new File([u8arr], filename, { type: mime });
}

/**
 * 图片转base64
 * file: 要编码的图片
 * return: Promise
 * */

function img2base(file) {
  return new Promise(res => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = r => {
      res(r.target.result);
    };
  });
}

/**

 * 10位时间戳转化为年 月 日 时 分 秒

 * number: 传入时间戳

 * format：返回格式

 */

function formatTime(number, format = 'Y-MM-DD HH:mm:ss') {
  let date = number instanceof Date ? number : !isNaN(number) ? new Date(number * 1000) : false;
  if (date === false) {
    return '————';
  }

  let regs = {
    'Y': date.getFullYear(),
    'M': date.getMonth() + 1,
    'D': date.getDate(),
    'd': ['日', '一', '二', '三', '四', '五', '六'][date.getDay()],
    'H': date.getHours(),
    'm': date.getMinutes(),
    's': date.getSeconds()
  };

  format = format.replace(/[ymdhs]+/ig, e => {
    let val = regs[e[0]];
    if (e.length === 2 && e[0] !== 'd') {
      return ('00' + val).slice(-2);
    } else {
      return val;
    }
  });

  return format;

}

/**
 * 检查是否为文件
 * params file 文件
 */

function isFileType(file) {
  const isFile = /\.((xls|doc|ppt)x?|pdf)$/i.test(file.name);
  const isType = /^((image\/(jpeg|png|gif))|(application\/(zip|pdf))|(audio\/(mp3|mpeg))|video\/mp4)$/i.test(file.type);
  return isFile || isType;
}

/**
 * 检查微信授权
 * fullPath 获取微信授权后跳转路径
 */

async function checkWxToken(fullPath) {
  if (store.state.wxUserInfo.unionid && store.state.wxUserInfo.openid) return store.state.wxUserInfo;
  let _params = {};
  // get url query
  let queryArr = location.search.slice(1);
  if (queryArr) {
    queryArr = queryArr.split('&');
  }
  let query = {};
  queryArr && queryArr.map(e => {
    let arr = e.split('=');
    query[arr[0]] = decodeURIComponent(arr[1]);
  });

  // check code
  // alert('query:::' + JSON.stringify(query));
  let wx_code = query.code;
  let state = query.state;
  // alert('wx_code:::' + wx_code);
  fullPath = encodeURIComponent(fullPath);
  if (!state) {
    router.replace('/auth?path=' + fullPath);
    throw 'auth';
  } else if (!wx_code) {
    router.go(-1);
    throw 'cancel';
  } else {
    try {
      let res = await http.$post('wxcat/api/get_wx_userinfo_reg', {
        code: wx_code
      });
      _params.nickname = res.nickname;
      res.nickname = '\\u' + res.nickname.split('').map(s => ('0000' + s.charCodeAt().toString(16)).slice(-4)).join('\\u');
      _params.realname = res.nickname;
      _params.unionid = res.unionid;
      _params.openid = res.openid;
      _params.icon = res.headimgurl;
      _params.uid = res.uid || '';
      _params.is_register = res.is_register || false;
      _params.content = res;
      store.commit('setWxUserInfo', _params);
      return store.state.wxUserInfo;
    } catch (err) {
      if (err.code && (err.code * 1 !== 201)) {
        router.replace('/auth?path=' + fullPath);
        throw 'auth';
      } else {
        throw err;
      }
    }
  }
}

/**
 * 登录
 * uid 邀请人uid， 有值则为分销注册
 * fullPath 获取微信授权后跳转路径
 * */
async function login(uid = '', fullPath = '') {
  // if (store.state.isLogin) return 'isLogin';
  // store.commit('setIsLogin', true);
  try {
    let { wxUserInfo, productInfo } = store.state;
    if (!wxUserInfo.openid || !wxUserInfo.unionid) {
      await checkWxToken(fullPath);
    }
    let { openid, unionid, realname, icon, content } = store.state.wxUserInfo;
    let res = await http.$post('wxcat/api/register_fenxiao', {
      ...productInfo,
      openid,
      unionid,
      realname,
      icon,
      content,
      uid,
      is_get_reward: uid ? 1 : ''
    });
    store.commit('setIsLogin', false);
    store.commit('setUserInfo', { uid: res.uid });
    return store.state.userInfo;
  } catch (e) {
    store.commit('setIsLogin', false);
    throw e;
  }
}

/**
 * 跳转播放页面
 * */

function goToPlay(item = {}, canPlay, cannotPlay, beforeStop, close) {
  close = typeof close === 'function' ? close : new Function();
  cannotPlay = typeof cannotPlay === 'function' ? cannotPlay : () => {
    // 跳转购买会员页面
    router.push({
      name: 'PayVip',
      params: {
        id: store.state.productInfo.product_id
      }
    });
  };
  if (item.is_free || item.is_pay * 1 === 1 || store.state.userInfo.is_vip) {
    if (!canPlay) {
      // 去播放页面
      router.push({
        name: 'PlayVideo',
        params: {
          vid: item.id,
          cid: item.course_id
        }
      });
    } else {
      canPlay();
    }
  } else {
    // 禁止跳转
    typeof beforeStop === 'function' && beforeStop();
    let Stop = Vue.extend(require('../base/notvip').default);
    let stop = new Stop({ el: document.createElement('div') });
    stop.$on('btn-click', cannotPlay);
    stop.$on('close', close);
    document.body.appendChild(stop.$el);
    return stop;
  }
}

/**
 * 设置微信js-sdk config
 * */

function setWxConfig(jsApiList = [], url = location.href.split('#')[0]) {
  jsApiList = [
    ...jsApiList
    // 'updateAppMessageShareData',
    // 'updateTimelineShareData',
    // 'onMenuShareTimeline', // 旧的接口，即将废弃
    // 'onMenuShareAppMessage' // 旧的接口，即将废弃
  ];
  let params = {
    url,
    product_id: 0 //
  };
  return http.$post('wxcat/api/get_sign', params).then(res => {
    res = res.sign;
    let wxConfig = {
      // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: res.app_id, // 必填，公众号的唯一标识
      timestamp: res.timestamp, // 必填，生成签名的时间戳
      nonceStr: res.noncestr, // 必填，生成签名的随机串
      signature: res.sign, // 必填，签名
      jsApiList // 必填，需要使用的JS接口列表
    };
    wx.config(wxConfig);
    return res;
  });
}

/**
 * 获取用户详情
 * */

async function getUserInfoApi(uid = store.state.userInfo.uid, product_id = store.state.productInfo.product_id) {
  let res = await http.$post('api/user/get_user_data', { uid, product_id });
  store.commit('setUserInfo', res);
  return res;
}

/**
 * 获取年级列表
 * */

async function getGradesApi(type_id = 3) {
  let grades = await http.$post('api/resource.tag/get_type', { type_id, pid: isXxtb ? 2 : '' });
  let gradeList = grades.filter(e => {
    if (e.name === '初中六年级') {
      e.name = '五四制';
    }
    e.name = e.name.slice(-3);
    return e.short_name !== '高';
  });
  if (!isXxtb) {
    gradeList.push(...[
      { id: 4001, section: 4, name: '高一' },
      { id: 4002, section: 4, name: '高二' },
      { id: 4003, section: 4, name: '高三' }
    ]);
  }
  store.commit('setGrades', gradeList);
  return [...gradeList];
}

/**
 * 刷新页面
 * key 保存storage时使用的key
 * @return
 * */

function reload(key = 'reload') {
  if (localStorage.getItem(key)) {
    localStorage.removeItem(key);
    return false;
  } else {
    localStorage.setItem(key, '1');
    let url = location.href;
    if (!/\?(.+)?#/.test(url)) {
      url = url.replace('#', '?#');
    } else {
      url = url.replace(/(&_=\d+)?#/i, `&_=${new Date().getTime()}#`);
    }
    location.replace(url);
    return true;
  }
}

/**
 * 秒数转为对应时间
 * */

function num2time(num, format = 'd天h:m:s') {
  num = parseInt(num);
  if (!num) return '00:00:00';
  let smhd = {
    s: num % 60,
    m: (num % (60 * 60) / 60) | 0,
    h: (num % (60 * 60 * 24) / 60 / 60) | 0,
    d: (num / 60 / 60 / 24) | 0
  };
  return format.replace(/[smhd]/g, s => ('00' + smhd[s]).slice(-2)).replace(/^00((?!(\d{2}:))[^])*(00:)?/, '');
}


/**
 * @desc 毫秒数转时间 (日D 时H 分m 秒s 毫秒S)
 * @param {number} number 要转换的毫秒数
 * @param {string} [format] 转换的格式
 * @return String
 * */
function numberToTime(number, format = 'HH:mm:ss') {
  number = isNaN(number) ? 0 : (number || 0);
  let regs = {
    S: number | 0,
    s: number / 1000 | 0,
    m: number / 1000 / 60 | 0,
    H: number / 1000 / 60 / 60 | 0,
    D: number / 1000 / 60 / 60 / 24 | 0
  };
  // 保留要输出的最高位 如：防止 format = 'mm:ss' 时 '60:00' 变为 '00:00'
  if (format.indexOf('s') >= 0) regs.S %= 1000;
  if (format.indexOf('m') >= 0) regs.s %= 60;
  if (format.indexOf('H') >= 0) regs.m %= 60;
  if (format.indexOf('D') >= 0) regs.H %= 24;

  format = format.replace(/([smhd])\1*/ig, e => {
    let val = regs[e[0]] || 0;
    val += '';
    if (e.length === 2 && val.length < 2) {
      return e.indexOf('S') < 0 ? '0' + val : val.slice(0, 2);
    } else {
      return val;
    }
  });
  return format;
}

/**
 * 更新缓存数据
 * @param right 马上更新
 * */
function autoUpdateLocal(right) {
  let { autoUpdateTime, updateTime, userInfo, wxUserInfo } = store.getters;
  let now = +new Date();
  if (right || now < updateTime || now - updateTime > autoUpdateTime) {
    store.commit('setUpdateTime', now);
    store.commit('setAllCourse', {});
    let oldUser = localStorage.getItem('user');
    localStorage.removeItem('user');
    oldUser = oldUser ? JSON.parse(oldUser) : {};
    if (
      userInfo.uid ||
      oldUser.uid ||
      (wxUserInfo.openid && wxUserInfo.unionid)
    ) {
      // 已经登录，重新获取用户信息 或 登录中已经获取用户微信信息
      store.commit('setUserInfo', { uid: userInfo.uid });
    }
    getGradesApi();
  }
}


/**
 * @desc 返回当前日期的相对时间段
 * @function
 * @params {number/string} val:
 *         类型 n(近n天) , tm(本月), ty(本年), nlm(前n月), nly(前n年), nm(近n月), ny(近n年)
 * @params {number/string/date} [date]:
 *         基本日期，默认不传，即为当天
 * @return {array} [start(00:00:00), end(23:59:59)]
 */
function typeToDate(val, date) {
  if (typeof val !== 'number' && typeof val !== 'string') return [,];
  let start = date ? new Date(date) : new Date();
  let end = date ? new Date(date) : new Date();
  let num = parseInt(val);
  if (!isNaN(val)) {
    // 近num天 num
    val && start.setDate(start.getDate() - num);
  } else if (/tm$/i.test(val)) {
    // 本月 tm
    start.setDate(1);
    end.setMonth(end.getMonth() + 1);
    end.setDate(0);
  } else if (/ty$/i.test(val)) {
    // 本年 ty
    start.setMonth(0);
    start.setDate(1);
    end.setMonth(11);
    end.setDate(31);
  } else if (/l$/i.test(val)) {
    // 前num天 nl
    end.setDate(end.getDate() - 1);
    start.setDate(start.getDate() - num);
  } else if (/lm$/i.test(val)) {
    // 前num个月 nlm
    end.setDate(0);
    start.setMonth(start.getMonth() - num);
    start.setDate(1);
  } else if (/ly$/i.test(val)) {
    // 前num年 nly
    end.setMonth(-1);
    end.setDate(31);
    start.setFullYear(start.getFullYear() - num);
    start.setMonth(0);
    start.setDate(1);
  } else if (/m$/i.test(val)) {
    // 近num月 nm
    start.setMonth(start.getMonth() - num);
  } else if (/y$/i.test(val)) {
    // 近num年 ny
    start.setFullYear(start.getFullYear() - num);
  }
  let arr = [start, end];
  arr = arr.map((d, i) => new Date(formatTime(d, 'Y-M-D ' + (!i ? '00:00:00' : '23:59:59'))));
  return arr;
}

/**
 * 生成分享路径
 * */
function makeShareLink() {
  let { product_id, channel_id, title } = store.getters.productInfo;
  let url = location.href;
  let key = Base64.encode(`${product_id}&${channel_id}&${title || isXxtb ? '同步小学课堂' : '中小学辅导班'}`);
  if (url.indexOf('?key=') === -1) {
    url += '?key=' + encodeURIComponent(key);
  }
  return url;
}


/**
 * 复制文本到剪切板
 * @param {String | number} text 要复制的文本
 * @return Boolean
 * */
function copyText(text) {
  let input = document.createElement('input');
  input.style.position = 'fixed';
  input.style.top = '-1000px';
  document.body.appendChild(input);
  input.value = text;
  input.select();
  let res = document.execCommand('copy');
  document.body.removeChild(input);
  return res;
}


window.autoUpdateLocal = autoUpdateLocal;

module.exports = {
  formatTime,
  typeToDate,
  isFileType,
  base2img,
  img2base,
  goToPlay,
  checkWxToken,
  login,
  setWxConfig,
  getUserInfoApi,
  getGradesApi,
  reload,
  num2time,
  numberToTime,
  copyText,
  makeShareLink,
  autoUpdateLocal
};
